package com.xctech.ipb.dpn.hyc.controller;

import com.xctech.ipb.dpn.common.utils.JsonUtils;
import com.xctech.ipb.dpn.common.vo.Result;
import com.xctech.ipb.dpn.framework.cache.service.FileCacheService;
import com.xctech.ipb.dpn.hyc.constant.TopicConstants;
import com.xctech.ipb.dpn.hyc.domain.service.DeviceService;
import com.xctech.ipb.dpn.hyc.model.dto.FileCacheMessage;
import com.xctech.ipb.dpn.hyc.model.req.DeviceReq;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import static com.xctech.ipb.dpn.common.response.ResponseCode.SUCCESS;

@RestController
@RequestMapping("/device")
@Slf4j
public class DeviceController {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private FileCacheService fileCacheService;

    //增量同步设备
    @PostMapping("/sync")
    public Result<String> sync(@Valid @RequestBody DeviceReq req) {
        log.info("device_sync 数量:{}", req.getListSize());

        String topicBody = JsonUtils.toJsonString(req);
        kafkaTemplate.send(TopicConstants.TOPIC_DEVICE_SYNC, topicBody);

        return Result.successOne(SUCCESS.name());
    }

    //全量同步设备
    @PostMapping("/syncAll")
    public Result<String> syncAll(@Valid @RequestBody DeviceReq req) {
        log.info("device_syncAll 数量:{}", req.getListSize());
        String fileName = fileCacheService.cacheData(req.getDeviceInfoList(), TopicConstants.TOPIC_DEVICE_SYNC_ALL);
        // 发送文件标识到队列
        FileCacheMessage message = new FileCacheMessage();
        message.setFileName(fileName);
        message.setFileType(TopicConstants.TOPIC_DEVICE_SYNC_ALL);
        message.setRecordCount(req.getListSize());
        message.setCreateTime(System.currentTimeMillis());

        String topicBody = JsonUtils.toJsonString(message);
        kafkaTemplate.send(TopicConstants.TOPIC_DEVICE_SYNC_ALL, topicBody);
        return Result.successOne(SUCCESS.name());
    }

}
